// Copyright (c) [2021] [daifang]
// [Dcomponent] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//          http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
import { bool, func, number, object, string } from 'prop-types';
import { useState, useEffect, useContext } from 'react';
import { Context, FieldContext } from '../index'
import '../style.less'

function TextArea(props) {
    let { onChange, maxLength, count,countText, width, style, defalutValue, placeholder } = props
    let [value, setValue] = useState(defalutValue || '')
    const {formData, setFormData} = useContext(Context)
    const {setItemVal, name, isPass} = useContext(FieldContext)
    useEffect(() => {
        // console.log(index,'didT')
        if(formData[name]) formData[name].value = value
        if(setItemVal) setItemVal(value)
            
        // console.log(formData[name], 'did')
        setFormData(formData)
        // setFormData(formData)
        return () => {}
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [value])
    return <div className={`d-textArea ${isPass?'':'inputError'}`}>
        <textarea
            placeholder={placeholder}
            maxLength={maxLength}
            value={value}
            onInput={(e)=>{
                let val = e.target.value
                setValue(val)
                if(onChange){
                    onChange(val)
                } 
            }}
            style={{
                width:`${width}px`,
                ...style
            }}
        />
        {count && <span className='count'>{countText?countText:`${value.length} / ${maxLength}`}</span>}
    </div>
}

TextArea.propTypes = {
    onChange:func,
    maxLength:number,
    count:bool,
    option:object,
    countText:string,
    placeholder:string
}
export default TextArea